import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/components/layout/Layout.vue'

// 导入路由模块
import jobRoutes from './modules/job'
import logRoutes from './modules/log'

Vue.use(VueRouter)

// 公共路由
const publicRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/Index.vue'),
        meta: { title: '控制台', icon: 'el-icon-s-home' }
      },
      {
        path: 'about',
        name: 'About',
        component: () => import('@/views/system/About.vue'),
        meta: { title: '关于系统', icon: 'el-icon-info' }
      }
    ]
  }
]

// 合并所有路由
const routes = [...publicRoutes, ...jobRoutes, ...logRoutes]

const router = new VueRouter({
  mode: 'history',
  base: import.meta.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - ${import.meta.env.VITE_APP_TITLE}` : import.meta.env.VITE_APP_TITLE
  
  // 登录验证
  const isLogin = localStorage.getItem('token')
  if (to.path === '/login') {
    next()
  } else {
    if (isLogin) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
